import React, { useState, useCallback, useEffect } from 'react';
import { View, ScrollView, StyleSheet, TextInput, ActivityIndicator, Dimensions, TouchableOpacity, Pressable, Platform } from 'react-native';
import { useTheme } from '../components/theme/ThemeContext';
import { ThemedText } from '../components/ThemedText';
import { ThemedView } from '../components/ThemedView';
import { Header } from '../components/Header';
import { ArtworkCard } from '../components/ArtworkCard';
import { artworkService } from '../utils/api/services';
import { ArtworkResponse } from '../utils/api/types';
import { MaterialIcons } from '@expo/vector-icons';
import { getFullURL } from '../utils/url';
import { useRouter } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import Constants from 'expo-constants';
import _ from 'lodash';

const { width } = Dimensions.get('window');
const ARTWORK_MARGIN = 8;
const ARTWORK_WIDTH = (width - 48) / 2; // 左右各16padding + 中间16间距

// 作品分类
const CATEGORIES = [
  { id: 'all', name: '全部' },
  { id: 'text', name: '文字' },
  { id: 'image', name: '图片' },
  { id: 'audio', name: '音频' },
  { id: 'video', name: '视频' },
  { id: 'code', name: '代码' },
];

export default function SearchScreen() {
  const { theme } = useTheme();
  const router = useRouter();
  const [searchText, setSearchText] = useState('');
  const [selectedCategory, setSelectedCategory] = useState('all');
  const [selectedTags, setSelectedTags] = useState<string[]>([]);
  const [availableTags, setAvailableTags] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);
  const [searchResults, setSearchResults] = useState<ArtworkResponse[]>([]);

  // 获取所有标签
  useEffect(() => {
    const fetchTags = async () => {
      try {
        const response = await artworkService.getTags();
        if (response?.data?.length > 0) {
          setAvailableTags(response.data.map((tag: { name: string }) => tag.name));
        }
      } catch (err) {
        console.error('获取标签失败:', err);
      }
    };
    fetchTags();
  }, []);

  // 执行搜索
  const performSearch = useCallback(async (params: any) => {
    try {
      setLoading(true);
      setError(null);

      console.log('搜索参数:', params);
      const response = await artworkService.listArtworks(params);
      console.log('搜索响应:', response);

      if (response?.code === 200) {
        console.log('原始数据:', response.data);
        const paginatedData = response.data as unknown as { items: ArtworkResponse[]; count: number };
        console.log('数据类型:', Array.isArray(paginatedData.items) ? 'Array' : typeof paginatedData.items);
        
        const artworks = paginatedData.items.map((artwork: ArtworkResponse) => {
          console.log('处理作品:', artwork);
          return {
            ...artwork,
            file_url: artwork.file_url ? (
              artwork.file_url.startsWith('http') ? artwork.file_url : getFullURL(artwork.file_url)
            ) : '',
            creator_id: artwork.creator_id || 0,
            description: artwork.description || '',
            tags: artwork.tags || []
          };
        });
        console.log('处理后的作品列表:', artworks);
        setSearchResults(artworks);
      } else {
        console.warn('搜索响应异常:', response);
        setSearchResults([]);
      }
    } catch (err: any) {
      console.error('搜索失败:', err);
      if (err.response) {
        console.error('错误响应:', err.response);
        console.error('错误状态:', err.response.status);
        console.error('错误数据:', err.response.data);
      }
      setError(err.message || '搜索失败，请重试');
      setSearchResults([]);
    } finally {
      setLoading(false);
    }
  }, []);

  // 使用防抖处理搜索
  const debouncedSearch = useCallback(
    _.debounce((text: string) => performSearch({
      limit: 20,
      offset: 0,
      keywords: text.trim(),
      category: selectedCategory,
      tag: selectedTags[0]
    }), 500),
    [selectedCategory, selectedTags, performSearch]
  );

  // 处理搜索输入
  const handleSearchInput = (text: string) => {
    setSearchText(text);
    debouncedSearch(text);
  };

  // 处理分类选择
  const handleCategorySelect = (category: string) => {
    console.log('选择分类:', category);
    setSelectedCategory(category);
    // 使用最新的category值而不是依赖selectedCategory状态
    const params: any = {
      limit: 20,
      offset: 0,
    };

    if (searchText?.trim()) {
      params.keywords = searchText.trim();
    }
    
    // 只有在不是 'all' 的情况下才添加 category
    if (category !== 'all') {
      params.category = category;
    }

    if (selectedTags.length > 0) {
      params.tag = selectedTags[0];
    }

    performSearch(params);
  };

  // 处理标签选择
  const handleTagSelect = (tag: string) => {
    const newTags = selectedTags.includes(tag)
      ? selectedTags.filter(t => t !== tag)
      : [tag]; // 目前只支持单个标签
    setSelectedTags(newTags);
    
    const params: any = {
      limit: 20,
      offset: 0,
      keywords: searchText,
    };

    // 只有在不是 'all' 的情况下才添加 category
    if (selectedCategory !== 'all') {
      params.category = selectedCategory;
    }

    // 只有在有标签的情况下才添加 tag
    if (newTags.length > 0) {
      params.tag = newTags[0];
    }

    performSearch(params);
  };

  // 处理返回
  const handleBack = () => {
    router.back();
  };

  return (
    <ThemedView style={styles.container}>
      <StatusBar style="auto" />
      {/* 头部搜索区 */}
      <View style={[styles.header, { backgroundColor: theme.colors.card }]}>
        <TouchableOpacity 
          onPress={handleBack} 
          style={styles.backButton}
          hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
        >
          <MaterialIcons 
            name="arrow-back" 
            size={24} 
            color={theme.colors.text}
          />
        </TouchableOpacity>
        
        <View style={[styles.searchInputContainer, { backgroundColor: theme.colors.background }]}>
          <MaterialIcons 
            name="search" 
            size={20} 
            color={theme.colors.text + '80'}
          />
          <TextInput
            style={[
              styles.searchInput,
              { color: theme.colors.text }
            ]}
            placeholder="输入关键词搜索作品..."
            placeholderTextColor={theme.colors.text + '80'}
            value={searchText}
            onChangeText={handleSearchInput}
            returnKeyType="search"
            autoFocus={true}
          />
          {searchText ? (
            <TouchableOpacity 
              onPress={() => handleSearchInput('')}
              hitSlop={{ top: 10, bottom: 10, left: 10, right: 10 }}
            >
              <MaterialIcons 
                name="close" 
                size={20} 
                color={theme.colors.text + '80'}
              />
            </TouchableOpacity>
          ) : null}
        </View>
      </View>

      {/* 筛选器区域 */}
      <View style={styles.filtersWrapper}>
        <ScrollView 
          horizontal 
          showsHorizontalScrollIndicator={false}
          style={styles.filtersContainer}
          contentContainerStyle={styles.filtersContent}
        >
          {CATEGORIES.map(category => (
            <Pressable
              key={category.id}
              style={[
                styles.categoryChip,
                { 
                  backgroundColor: selectedCategory === category.id 
                    ? theme.colors.primary 
                    : theme.colors.card 
                }
              ]}
              onPress={() => handleCategorySelect(category.id)}
            >
              <ThemedText
                style={{
                  ...styles.categoryText,
                  color: selectedCategory === category.id 
                    ? theme.colors.card 
                    : theme.colors.text 
                }}
              >
                {category.name}
              </ThemedText>
            </Pressable>
          ))}
        </ScrollView>

        {availableTags.length > 0 && (
          <ScrollView 
            horizontal 
            showsHorizontalScrollIndicator={false}
            style={styles.filtersContainer}
            contentContainerStyle={styles.filtersContent}
          >
            {availableTags.map(tag => (
              <Pressable
                key={tag}
                style={[
                  styles.tagChip,
                  { 
                    backgroundColor: selectedTags.includes(tag)
                      ? theme.colors.primary 
                      : theme.colors.card 
                  }
                ]}
                onPress={() => handleTagSelect(tag)}
              >
                <ThemedText
                  style={{
                    ...styles.tagText,
                    color: selectedTags.includes(tag)
                      ? theme.colors.card 
                      : theme.colors.text 
                  }}
                >
                  #{tag}
                </ThemedText>
              </Pressable>
            ))}
          </ScrollView>
        )}
      </View>

      {/* 结果区域 */}
      {loading ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color={theme.colors.primary} />
          <ThemedText style={styles.loadingText}>搜索中...</ThemedText>
        </View>
      ) : error ? (
        <View style={styles.errorContainer}>
          <ThemedText style={styles.errorText}>{error}</ThemedText>
        </View>
      ) : (
        <ScrollView 
          style={styles.resultsContainer}
          contentContainerStyle={styles.resultsContent}
        >
          {searchResults.length > 0 ? (
            <View style={styles.resultsGrid}>
              {searchResults.map((artwork) => (
                <View key={artwork.id} style={styles.artworkContainer}>
                  <ArtworkCard
                    artwork={artwork}
                    variant="recent"
                  />
                </View>
              ))}
            </View>
          ) : (
            <View style={styles.emptyContainer}>
              <MaterialIcons 
                name="search-off" 
                size={48} 
                color={theme.colors.text + '40'}
              />
              <ThemedText style={styles.emptyText}>
                {searchText || selectedCategory !== 'all' || selectedTags.length > 0
                  ? '未找到相关作品'
                  : '输入关键词开始搜索'
                }
              </ThemedText>
            </View>
          )}
        </ScrollView>
      )}
    </ThemedView>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  header: {
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    paddingTop: Constants.statusBarHeight + 8,
    height: Constants.statusBarHeight + 64,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: 'rgba(0,0,0,0.1)',
    ...Platform.select({
      ios: {
        shadowColor: '#000',
        shadowOffset: { width: 0, height: 1 },
        shadowOpacity: 0.1,
        shadowRadius: 1,
      },
      android: {
        elevation: 2,
      },
    }),
  },
  backButton: {
    marginRight: 12,
    padding: 4,
  },
  searchInputContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    paddingHorizontal: 16,
    height: 44,
    borderRadius: 22,
    marginVertical: 8,
  },
  searchInput: {
    flex: 1,
    fontSize: 16,
    paddingHorizontal: 12,
    height: '100%',
    marginHorizontal: 8,
  },
  filtersWrapper: {
    paddingVertical: 8,
    borderBottomWidth: StyleSheet.hairlineWidth,
    borderBottomColor: 'rgba(0,0,0,0.1)',
  },
  filtersContainer: {
    flexGrow: 0,
  },
  filtersContent: {
    paddingHorizontal: 16,
  },
  categoryChip: {
    paddingHorizontal: 16,
    paddingVertical: 8,
    borderRadius: 16,
    marginRight: 8,
    marginVertical: 4,
  },
  categoryText: {
    fontSize: 14,
    fontWeight: '500',
  },
  tagChip: {
    paddingHorizontal: 12,
    paddingVertical: 6,
    borderRadius: 12,
    marginRight: 8,
    marginVertical: 4,
  },
  tagText: {
    fontSize: 12,
    fontWeight: '500',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  loadingText: {
    marginTop: 12,
    opacity: 0.6,
  },
  errorContainer: {
    flex: 1,
    padding: 16,
    justifyContent: 'center',
    alignItems: 'center',
  },
  errorText: {
    textAlign: 'center',
    color: 'red',
  },
  resultsContainer: {
    flex: 1,
  },
  resultsContent: {
    padding: 16,
  },
  resultsGrid: {
    flexDirection: 'row',
    flexWrap: 'wrap',
    marginHorizontal: -ARTWORK_MARGIN,
  },
  artworkContainer: {
    width: ARTWORK_WIDTH,
    margin: ARTWORK_MARGIN,
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingTop: 80,
  },
  emptyText: {
    marginTop: 12,
    opacity: 0.4,
  },
}); 